<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('姓名')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('姓名')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('证件类型')" prop="idType">
            <dictSelect
              v-model="form.idType"
              :clearable="true"
              dictionary="hr_id_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('证件号码')" prop="idNum">
            <el-input v-model="form.idNum" :placeholder="$t('证件号码')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('性别')" prop="sex">
            <dictSelect
              v-model="form.sex"
              :clearable="true"
              dictionary="sys_user_sex"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('年龄')" prop="age">
            <el-input v-model="form.age" oninput="value=value.replace(/[^\d]/g,'')" :placeholder="$t('年龄')" show-word-limit maxlength="10" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('学历')" prop="education">
            <el-input v-model="form.education" :placeholder="$t('学历')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('学校')" prop="school">
            <el-input v-model="form.school" :placeholder="$t('学校')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('专业')" prop="major">
            <el-input v-model="form.major" :placeholder="$t('专业')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('拟到职日期')" prop="entryTime">
            <el-date-picker
              v-model="form.entryTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('到职日期')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('拟录部门')" prop="deptId">
            <tree-select v-model="form.deptId" node-key="id" :default-expand-all="true" :data="initData.deptOptions" :placeholder="$t('请选择')">
              <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                {{ $t(node.label) }}
                <span v-if="shouldShowCount" :class="countClassName">({{ count }})</span>
              </label>
            </tree-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('拟录职位')" prop="postId">
            <el-select v-model="form.postId">
              <el-option
                v-for="(item) in initData.hrPositions"
                :key="item.id"
                :label="$t(item.postName)"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('薪资福利（月薪）') + $t('金额单位')" prop="salary">
            <money v-model="form.salary" :placeholder="$t('薪资福利（月薪）')+$t('金额单位')" unit="w" @change="changeSalary" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同期限')" prop="contractTerm">
            <dictSelect
              v-model="form.contractTerm"
              :clearable="true"
              dictionary="hr_contract_period"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('试用期')" prop="probation">
            <dictSelect
              v-model="form.probation"
              :clearable="true"
              dictionary="hr_trial_type"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('试用期薪资（月薪）') + $t('金额单位')" prop="probationSalary">
            <money v-model="form.probationSalary" :placeholder="$t('薪资福利（月薪）') + $t('金额单位')" unit="w" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('关联用户')" prop="userId">
            <UserSelect v-model="form.userId" :placeholder="$t('关联用户')" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>

      </el-row>
      <!--文件-->
      <FileTable :list.sync="form.fileList" :data-type="dataType" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="hr:entry" :menu-key="menuKey" />
    </div>

    <!-- 预览附件 -->
    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
import { saveHrEntry, getHrEntry, checkUserId } from '@/api/oa/hr/hrEntry'
import { treeselect } from '@/api/system/dept'
import TreeSelect from '@/components/TreeSelect'
import { listPost } from '@/api/system/post'
export default {
  components: { TreeSelect },
  data() {
    return {
      // 菜单标识
      menuKey: this.$t('hr_entry'),
      otherBtnHide: false,
      dataType: 'hr_entry',
      // 表单参数
      form: {
        fileList: []
      },
      // 表单校验
      rules: {
        deptId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], postId: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], entryTime: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], name: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], idType: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], idNum: [
          { required: true, validator: this.checkIdNum, trigger: 'blur' }
        ], age: [
          { required: true, validator: this.checkAge, trigger: 'blur' }
        ], education: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], major: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], probation: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], sex: [
          { required: true, validator: this.checkSex, trigger: 'change' }
        ]
      },
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      initData: {
        deptOptions: [],
        hrPositions: []
      }
    }
  },
  created() {
    this.initDataMethod()
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      if (data != null && data.id !== undefined) {
        this.loading = true
        getHrEntry(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        actTitle: undefined,
        userId: undefined,
        deptId: undefined,
        contractTerm: undefined,
        postId: undefined,
        entryTime: undefined,
        name: undefined,
        workAddress: undefined,
        idType: undefined,
        idNum: undefined,
        age: undefined,
        education: undefined,
        school: undefined,
        major: undefined,
        salary: undefined,
        sex: undefined,
        probation: undefined,
        probationSalary: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    initDataMethod() {
      treeselect().then(response => {
        this.initData.deptOptions = response.data
      })
      // 职位
      listPost({}).then(response => {
        this.initData.hrPositions = response.rows
      })
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            this.form.actTitle = this.$t('入职申请')
            saveHrEntry(this.form).then(response => {
              if (response.code === 200) {
                this.form.id = response.data.id
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  // 启动流程
                  this.startProcess(response.data)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.name + ' ' + this.$t('入职申请')
      // 业务表名
      processData.dataTable = 'hr_entry'
      // 业务ID
      processData.dataId = dataId.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/oa/hr/entry/hrEntryForm'
      processData.viewPath = '@/views/oa/hr/entry/hrEntryView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 同一个用户不能再次录入
    async checkUser(rule, value, callback) {
      if (this.form.userId === undefined || this.form.userId === '') {
        callback(new Error(this.$t('必填信息')))
      }
      var check = {
        userId: this.form.userId,
        id: this.form.id
      }
      var checkRes = await checkUserId(check)
      if (checkRes) {
        callback()
      } else {
        callback(new Error(this.$t('该员工已存在，不能重复添加')))
      }
    },
    // 同一个用户不能再次录入
    async checkIdNum(rule, value, callback) {
      if (this.form.idNum === undefined || this.form.idNum === '') {
        return callback(new Error(this.$t('必填信息')))
      }
      if (this.form.idType === '1') {
        const year = new Date().getFullYear()
        if (this.form.idNum.length === 18) {
          this.form.sex = (Number(this.form.idNum[16]) % 2 === 0 ? 1 : 0) + ''
          this.form.age = year - Number(this.form.idNum[6] + this.form.idNum[7] + this.form.idNum[8] + this.form.idNum[9])
          callback()
        } else if (this.form.idNum.length === 15) {
          this.form.sex = (Number(this.form.idNum[14]) % 2 === 0 ? 1 : 0) + ''
          this.form.age = year - Number('19' + this.form.idNum[6] + this.form.idNum[7])
          callback()
        } else {
          return callback(new Error(this.$t('请检查证件号码')))
        }
      }
    },
    async checkAge(rule, value, callback) {
      if (this.form.age === undefined || this.form.age === '') {
        return callback(new Error(this.$t('必填信息')))
      }
      if (this.form.idType === '1') {
        const year = new Date().getFullYear()
        if (this.form.idNum.length === 18) {
          if (this.form.age !== (year - Number(this.form.idNum[6] + this.form.idNum[7] + this.form.idNum[8] + this.form.idNum[9]))) {
            return callback(new Error(this.$t('请检查年龄，与证件上不符')))
          }
          callback()
        } else if (this.form.idNum.length === 15) {
          if (this.form.age !== (year - Number('19' + this.form.idNum[6] + this.form.idNum[7]))) {
            return callback(new Error(this.$t('请检查年龄，与证件上不符')))
          }
          callback()
        }
      // else {
      //     return callback(new Error(this.$t('请检验') + this.$t('证件号码')))
      //   }
      }
    },
    async checkSex(rule, value, callback) {
      if (this.form.sex === undefined || this.form.sex === '') {
        return callback(new Error(this.$t('必填信息')))
      }
      if (this.form.idType === '1') {
        if (this.form.idNum.length === 18) {
          if (this.form.sex !== ((Number(this.form.idNum[16]) % 2 === 0 ? 1 : 0) + '')) {
            return callback(new Error(this.$t('请检查性别，与证件上不符')))
          }
          callback()
        } else if (this.form.idNum.length === 15) {
          if (this.form.sex !== ((Number(this.form.idNum[14]) % 2 === 0 ? 1 : 0) + '')) {
            return callback(new Error(this.$t('请检查性别，与证件上不符')))
          }
          callback()
        }
        // else {
        //   return callback(new Error(this.$t('请检验证件号码')))
        // }
      }
    },
    changeSalary() {
      this.form.probationSalary = this.form.salary
    }

  }

}
</script>
